package com.uplift.mobile.user.service.impl;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator.Builder;
import com.auth0.jwt.algorithms.Algorithm;
import com.github.pagehelper.PageHelper;
import com.uplift.common.Const;
import com.uplift.common.utils.UUIDGenerater;
import com.uplift.mobile.sys.model.DictModel;
import com.uplift.mobile.sys.service.IDictService;
import com.uplift.mobile.user.dao.UserMapper;
import com.uplift.mobile.user.model.User;
import com.uplift.mobile.user.model.UserInfo;
import com.uplift.mobile.user.service.IUserService;
import com.uplift.sec.SecurityContext;

@Service
@Transactional
public class UserServiceImpl implements IUserService {

	@Autowired
	private UserMapper userMapper;

	@Autowired
	private IDictService dictService;
	
	@Autowired
	private JavaMailSender mailSender;

//	@Autowired
//	private TaskExecutor taskExecutor;

	@Override
	public List<Map<String, Object>> queryUser(User user) {
		PageHelper.startPage(user.getPage(), user.getPage());
		return this.userMapper.selectUser(user);
	}

	/**
	 * 状态说明，0：账号或密码错误，1：登录成功，2：账号或密码为空，3：被停用
	 */
	@Override
	public int login(HttpServletRequest request, User user) {
		int ret = 0;
		// 判断账号密码是否为空
		if (StringUtils.isBlank(user.getUsername()) || StringUtils.isBlank(user.getPassword())) {
			ret = 2;
		} else {
			List<Map<String, Object>> users = this.userMapper.selectUser(user);
			if (users != null && users.size() > 0) {
				Map<String, Object> userMap = users.get(0);
				String userId = MapUtils.getString(userMap, "id");
				String status = Objects.toString(userMap.get("state"));
				// 判断是否禁用
				if (StringUtils.equals("2", status)) {
					ret = 3;
				} else {
					// 过期时间设置
					Calendar c = Calendar.getInstance();
					// c.add(Calendar.HOUR_OF_DAY, Const.JWT_EXPIRES_24Hour);
					c.add(Calendar.YEAR, Const.JWT_EXPIRES_3YEAR);

					Algorithm algorithm = Algorithm.HMAC256(Const.JWT_SECRET);
					Builder builder = JWT.create();
					builder.withIssuer("auth0");
					builder.withExpiresAt(c.getTime());
					builder.withClaim("userId", userId);
					String token = builder.sign(algorithm);

					userMap.put("token", token);
					request.setAttribute(Const.REQUEST_USER, userMap);
					SecurityContext.setUserId(userId);
					ret = 1;
				}
			}
		}
		return ret;
	}

	@Override
	public int modifyUser(User user) {
		String userId = SecurityContext.getUserId();
		user.setId(userId);
		return this.userMapper.updateUser(user);
	}

	/**
	 * ret，0：失败，1：成功，2：原密码不正确
	 */
	@Override
	public int modifyPwd(User user) {
		int ret = 0;
		String userId = SecurityContext.getUserId();
		String oldPwd = user.getOldPassword();
		String newPwd = user.getNewPassword();

		user.setId(userId);
		List<Map<String, Object>> users = this.queryUser(user);
		if (users != null && users.size() > 0) {
			Map<String, Object> userMap = users.get(0);
			String password = MapUtils.getString(userMap, "password");
			// 用户输入的原密码与真实的原密码一致允许修改，不一致则返回状态
			if (StringUtils.equals(oldPwd, password)) {
				user.setPassword(newPwd);
				int row = this.userMapper.updateUser(user);
				if (row > 0) {
					ret = 1;
				}
			} else {
				ret = 2;
			}
		}

		return ret;
	}

	@Override
	public int findPwd(User user) {
		int ret = 0;
		List<Map<String, Object>> list = this.userMapper.selectUser(user);
		if (list != null && list.size() > 0) {
			Map<String, Object> map = list.get(0);
			String password = MapUtils.getString(map, "password");
			String recipientAddress = user.getEmail();
			String subject = "Uplife系统密码找回";
			String text = "<html><META http-equiv=Content-Type content='text/html; charset=UTF-8'><body>" + "亲爱的Uplife用户：<br/>" + "请您及时修改帐号的登录密码<br/>" + "&nbsp;&nbsp;密码："
					+ password + "<br/>" + "若您未申请密码找回，请忽略此邮件。<br/>";
			text += "</body></html>";
			try {
				MimeMessage message = this.mailSender.createMimeMessage();
				MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
				helper.setFrom(Const.MAIL_SENDER);
				helper.setTo(recipientAddress);
				helper.setSubject(subject);
				helper.setText(text, true);

//				this.taskExecutor.execute(new Runnable() {
//
//					@Override
//					public void run() {
//						mailSender.send(message);
//					}
//
//				});

				ret = 1;
			} catch (Exception e) {
				ret = 0;
			}
		}
		return ret;
	}

	@Override
	public int register(UserInfo userInfo) {
		int result = 0;
		
		boolean openRegister = false;
		
		DictModel dictModel = new DictModel();
		dictModel.setType("register");
		dictModel.setCode("OPEN_REGISTER");
		List<Map<String, Object>> dictList = this.dictService.queryDict(dictModel);
		if (dictList != null && dictList.size() > 0) {
			String valueStr = Objects.toString(dictList.get(0).get("value"));
			openRegister = StringUtils.equals("1", valueStr);
		}
		
		if (openRegister) {
			User user = new User();
			user.setUsername(userInfo.getUsername());
			List<Map<String, Object>> users = this.userMapper.selectUser(user);
			// 判断用户是否存在
			if (users == null || users.size() == 0) {
				userInfo.setCreateUserId("");
				userInfo.setId(UUIDGenerater.generate());
				userInfo.setState("1");
				userInfo.setCreateTime(new Date());
				result = this.userMapper.insertUser(userInfo);
			} else {
				result = -2;
			}
		} else {
			result = -1;
		}
		
		return result;
	}

}
